﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Xml;
using System.Threading;

namespace DISVotingButton
{
    class Functionality
    {
        static private XmlDocument xDoc = xDoc = new XmlDocument();
        static private DataBase dbc = null;
       
        static private string DISdbServer = "localhost\\SQLEXPRESS";
        static private string DISdb = "SW6000-1";
        static private string DISdb_user = "SW6K11";
        static private string DISdb_password = "HmAeC2005";
        public static int QuarumLimit = 13;
        public static int FormX = 640;
        public static int FormY = 688;
        public static bool reindex = false;
        static private string WebService = "http://localhost/webservice/service.asmx";
        static private List<Delegate> listDelegates=new List<Delegate>();

        public class Delegate
        {
            public string delegate_id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string dtype { get; set; }
            public string usertype { get; set; }
            public string UserTable1Text { get; set; }
            public string UserTable2Text { get; set; }
            public string UserTable3Text { get; set; }
            public string UserTable4Text { get; set; }
            public string group { get; set; }
            public string votegroup { get; set; }
            public string background { get; set; }
            public string photos { get; set; }
        }
   

        // get service startup path
        public static string StartPath
        {
            get
            {
                return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6);
            }
        }

        public static string ToTime(DateTime tm)
        {
            //tm.To
            string time = "00:00:00";
            string hours = tm.Hour.ToString();
            if (hours.Length == 1)
            {
                hours = "0" + hours;
            }
            string minutes = tm.Minute.ToString();
            if (minutes.Length == 1)
            {
                minutes = "0" + minutes;
            }
            string seconds = tm.Second.ToString();
            if (seconds.Length == 1)
            {
                seconds = "0" + seconds;
            }
            time = hours + ":" + minutes + ":" + seconds;
            return time;
        }

        public static string ToDate(DateTime tm)
        {
            string time = "00:00:00";
            string Years = tm.Year.ToString();
            string Months = tm.Month.ToString();
            if (Months.Length == 1)
            {
                Months = "0" + Months;
            }
            string Days = tm.Day.ToString();
            if (Days.Length == 1)
            {
                Days = "0" + Days;
            }
            time = Years + "-" + Months + "-" + Days;
            return time;
        }

        //get current date
        static public string getDate()
        {
            return ToDate(DateTime.Now);
        }

        //get current Time
        static public string getTime()
        {
            return ToTime(DateTime.Now);
        }

        // read service database connection parameters from xml
        public static void readXMLParameters()
        {
            try
            {
                XmlTextReader textReader = new XmlTextReader(StartPath + "\\config.xml");

                while (textReader.Read())
                {
                    XmlNodeType nType = textReader.NodeType;
                    if (nType == XmlNodeType.Element)
                    {
                        if (textReader.Name.ToString().Equals("DISDataBaseServer"))
                        {
                            DISdbServer = textReader.ReadElementContentAsString();
                        }
                        if (textReader.Name.ToString().Equals("DISDataBaseName"))
                        {
                            DISdb = textReader.ReadElementContentAsString();
                        }
                        if (textReader.Name.ToString().Equals("DISDataBaseUser"))
                        {
                            DISdb_user = textReader.ReadElementContentAsString();
                        }
                        if (textReader.Name.ToString().Equals("DISDataBasePassword"))
                        {
                            DISdb_password = textReader.ReadElementContentAsString();
                        }
                        if (textReader.Name.ToString().Equals("QuarumLimit"))
                        {
                            QuarumLimit = int.Parse(textReader.ReadElementContentAsString());
                        }
                        if (textReader.Name.ToString().Equals("WebService"))
                        {
                            WebService = textReader.ReadElementContentAsString();
                        }
                        if (textReader.Name.ToString().Equals("FormX"))
                        {
                            FormX = int.Parse(textReader.ReadElementContentAsString());
                        }
                        if (textReader.Name.ToString().Equals("FormY"))
                        {
                            FormY = int.Parse(textReader.ReadElementContentAsString());
                        }
                        if (textReader.Name.ToString().Equals("Reindex"))
                        {
                            reindex = bool.Parse(textReader.ReadElementContentAsString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                 AddToEventLog("DISdataCollecting", "Konfiguracijos skaitymo klaida: " + ex.Message, true);
            }
        }

        //add error to event list
        public static void AddToEventLog(string sSource, string sEvent, bool error)
        {
            string sLog = "Application";
            try
            {
                if (!EventLog.SourceExists(sSource))
                    EventLog.CreateEventSource(sSource, sLog);
                if (error)
                {
                    EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Error, 0);
                }
                else
                {
                    EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Information, 123);
                }
            }
            catch (Exception ex)
            {
                
            }
        }

        static void readDelegatesFromDISDatabase()
        {
              try
                {
                    string ConferrenceId = "-1";
                    string ConferrenceLoginMode = "-1";
                    DataBase dbcDIS = new DataBase(DISdbServer, DISdb_user, DISdb_password, DISdb);
                    String sql = "select * from Conference where active=1";
                    System.Data.DataTable tbci = dbcDIS.getTable(sql);
                    if (tbci.Rows.Count > 0)
                    {
                        if (tbci.Columns.Contains("id"))
                        {
                            ConferrenceId = tbci.Rows[0]["id"].ToString();
                        }
                        if (tbci.Columns.Contains("loginmode"))
                        {
                            ConferrenceLoginMode = tbci.Rows[0]["loginmode"].ToString();
                        }
                       
                    }
                    else
                    {
                        ConferrenceId = "-1";
                        ConferrenceLoginMode = "-1";
                    }


                    if (!ConferrenceLoginMode.Equals("1"))
                    {
                        //string DISsql = "select *,UserTypeText.name as dtype from DelegateText left join Delegate on Delegate.id=DelegateText.delegate_id left join UserTypeText on Delegate.usertype_id=UserTypeText.usertype_id where delegate_id in (select distinct delegate_id from LogDelegate where conference_id=" + ConferrenceId + " and loginTime>(select startTime from LogConference where conference_id=" + ConferrenceId + " and stoptime is null) and logoutTime is null and delegate_id in (select id from Delegate left join UserTypeText on Delegate.usertype_id=UserTypeText.usertype_id where UserTypeText.name like '%Tarybos narys%' or UserTypeText.name like '%Pirmininkaujantis%'))";
                        string DISsql = "select *,UserTypeText.name as dtype from DelegateText left join Delegate on Delegate.id=DelegateText.delegate_id left join UserTypeText on Delegate.usertype_id=UserTypeText.usertype_id where delegate_id in (select distinct delegate_id from LogDelegate where conference_id=" + ConferrenceId + " and loginTime>(select top(1) startTime from LogConference where conference_id=" + ConferrenceId + " order by starttime desc) and logoutTime is null and delegate_id in (select id from Delegate left join UserTypeText on Delegate.usertype_id=UserTypeText.usertype_id where UserTypeText.name like '%Tarybos narys%' or UserTypeText.name like '%Pirmininkaujantis%'))";
                        //AddToEventLog("DISButton", DISsql, false);
                        System.Data.DataTable tb = dbcDIS.getTable(DISsql);
                        if (tb.Rows.Count > 0)
                        {
                            listDelegates.Clear();
                            //dbc.procedure("clearDelegateInfoFinal");
                            for (int i = 0; i < tb.Rows.Count; i++)
                            {
                                string usertype = tb.Rows[i]["dtype"].ToString();
                                string votegroup = "";
                                string group = "";
                                string photos = "";
                                Delegate dl=new Delegate() { delegate_id = tb.Rows[i]["delegate_id"].ToString(), FirstName = tb.Rows[i]["FirstName"].ToString(), LastName = tb.Rows[i]["LastName"].ToString(), dtype = tb.Rows[i]["dtype"].ToString(), usertype = usertype, UserTable1Text = tb.Rows[i]["UserTable1Text"].ToString(), UserTable2Text = tb.Rows[i]["UserTable2Text"].ToString(), UserTable3Text = tb.Rows[i]["UserTable3Text"].ToString(), UserTable4Text = tb.Rows[i]["UserTable4Text"].ToString(), group = group, votegroup = votegroup, background = tb.Rows[i]["background"].ToString(), photos=photos };
                                if (!listDelegates.Contains(dl))
                                  { listDelegates.Add(dl); }
                                // dbc.insertDelegateInfoFinal(new string[] { (i).ToString(), tb.Rows[i]["delegate_id"].ToString(), tb.Rows[i]["FirstName"].ToString(), tb.Rows[i]["LastName"].ToString(), tb.Rows[i]["dtype"].ToString(), usertype, tb.Rows[i]["UserTable1Text"].ToString(), tb.Rows[i]["UserTable2Text"].ToString(), tb.Rows[i]["UserTable3Text"].ToString(), tb.Rows[i]["UserTable4Text"].ToString(), group, votegroup, tb.Rows[i]["background"].ToString(), photos, guid });
                            }
                        }
                    }
                    else if (ConferrenceLoginMode.Equals("1"))
                    {
                        //mod20130521 string DISsql = "select *,UserTypeText.name as dtype from DelegateText left join Delegate on Delegate.id=DelegateText.delegate_id left join UserTypeText on Delegate.usertype_id=UserTypeText.usertype_id where delegate_id in (select delegate_id from DelegateList where conference_id=" + ConferrenceId + ")";and ((starttime>=loginTime and logoutTime<=stoptime) or (starttime>=loginTime and logoutTime>=stoptime) or (starttime<=loginTime and stoptime>=loginTime and logoutTime>=stoptime)) 
                        string DISsql = "select *,UserTypeText.name as dtype from DelegateText left join Delegate on Delegate.id=DelegateText.delegate_id left join UserTypeText on Delegate.usertype_id=UserTypeText.usertype_id where delegate_id in (select delegate_id from DelegateList where conference_id=" + ConferrenceId + " and delegate_id in (select id from Delegate left join UserTypeText on Delegate.usertype_id=UserTypeText.usertype_id where UserTypeText.name like '%Tarybos narys%' or UserTypeText.name like '%Pirmininkaujantis%'))"; //and loginTime>(select startTime from LogConference where conference_id=" + ConferrenceId + " and stoptime is null) and logoutTime is null and
                        //AddToEventLog("DISButton", DISsql, false);
                        System.Data.DataTable tb = dbcDIS.getTable(DISsql);
                        if (tb.Rows.Count > 0)
                        {
                            listDelegates.Clear();
                           // dbc.procedure("clearDelegateInfoFinal");
                            for (int i = 0; i < tb.Rows.Count; i++)
                            {
                                string usertype = tb.Rows[i]["dtype"].ToString();
                                string votegroup = "";
                                string group = "";
                                string photos = "";
                                Delegate dl = new Delegate() { delegate_id = tb.Rows[i]["delegate_id"].ToString(), FirstName = tb.Rows[i]["FirstName"].ToString(), LastName = tb.Rows[i]["LastName"].ToString(), dtype = tb.Rows[i]["dtype"].ToString(), usertype = usertype, UserTable1Text = tb.Rows[i]["UserTable1Text"].ToString(), UserTable2Text = tb.Rows[i]["UserTable2Text"].ToString(), UserTable3Text = tb.Rows[i]["UserTable3Text"].ToString(), UserTable4Text = tb.Rows[i]["UserTable4Text"].ToString(), group = group, votegroup = votegroup, background = tb.Rows[i]["background"].ToString(), photos = photos };
                                if (!listDelegates.Contains(dl))
                                  { listDelegates.Add(dl); }
                               // dbc.insertDelegateInfoFinal(new string[] { (i).ToString(), tb.Rows[i]["delegate_id"].ToString(), tb.Rows[i]["FirstName"].ToString(), tb.Rows[i]["LastName"].ToString(), tb.Rows[i]["dtype"].ToString(), usertype, tb.Rows[i]["UserTable1Text"].ToString(), tb.Rows[i]["UserTable2Text"].ToString(), tb.Rows[i]["UserTable3Text"].ToString(), tb.Rows[i]["UserTable4Text"].ToString(), group, votegroup, tb.Rows[i]["background"].ToString(), photos, guid });
                            }
                        }
                    }
                    dbcDIS = null;
               
                }
                catch (Exception ex)
                {
                }
            
        }

        public static void writeVotingsToDB()
        {
            //startVoting("Bandomasis balsavimas", "200");
            listDelegates.Clear();
            readDelegatesFromDISDatabase();
            DataBase dbcDIS = new DataBase(DISdbServer, DISdb_user, DISdb_password, DISdb);
            String sql = "select Conference.id as confid, Agenda.Id as agendaid,AgendaText.Name as agendaname from Conference left join Agenda on Conference.id=Agenda.Conference_id left join AgendaText on Agenda.Id=AgendaText.Agenda_id where active=1 and Agenda.isCurrent=1 and AgendaText.Name not like '%Jokio klausimo%'";
            //AddToEventLog("VotingButton", sql, false);
            System.Data.DataTable tbci = dbcDIS.getTable(sql);
            string ConferrenceId = "";
            string Agenda_Id = "";
            string Agenda_Name = "";
            if (tbci.Rows.Count > 0)
            {
                if (tbci.Columns.Contains("confid"))
                {
                    ConferrenceId = tbci.Rows[0]["confid"].ToString();
                }
                if (tbci.Columns.Contains("agendaid"))
                {
                    Agenda_Id = tbci.Rows[0]["agendaid"].ToString();
                }
                if (tbci.Columns.Contains("agendaname"))
                {
                    Agenda_Name = tbci.Rows[0]["agendaname"].ToString();
                }
            }
            // DataBase dbc = new DataBase(dbServer, db_user, db_password, db);
            //string 
            if (!ConferrenceId.Equals("") && !Agenda_Id.Equals("") && !Agenda_Name.Equals(""))
            {
                if (listDelegates.Count >= QuarumLimit)
                {
                    startVoting(Agenda_Name, Agenda_Id);
                    Thread.Sleep(3000);
                    sql = "select * from ID;";
                   // AddToEventLog("VotingButton", sql, false);
                    System.Data.DataTable tbvs = dbcDIS.getTable(sql);
                    int voting_session_id = int.Parse(tbvs.Rows[0]["NextId"].ToString()) ;
                    //int voting_current_id = int.Parse(tbvs.Rows[0]["Id"].ToString()) ;
                    sql = "select MAX(version) from VotingSession where Conference_id=" + ConferrenceId + " and Agenda_id=" + Agenda_Id;
                    //AddToEventLog("VotingButton", sql, false);
                    tbvs = dbcDIS.getTable(sql);
                    int version=1;
                    try{
                       version=int.Parse(tbvs.Rows[0][0].ToString())+1;
                    }catch (Exception ex){}
                    string countdel = listDelegates.Count.ToString();
                    //sql = "insert into VotingSession values(" + voting_session_id.ToString() + "," + Agenda_Id + "," + ConferrenceId + ",1," + version.ToString() + ",'" + getDate() + " " + getTime() + "'," + countdel + ",0,0,0,0," + countdel + ",0," + countdel + "," + countdel + "," + countdel + ",1,1," + countdel + ",0,0,0," + countdel + ",0," + countdel + ",0,0,null);";
                    //sql = "insert into VotingSession values(" + voting_session_id.ToString() + "," + Agenda_Id + "," + ConferrenceId + ",1," + version.ToString() + ",CURRENT_TIMESTAMP," + countdel + ",0,0,0,0," + countdel + ",0," + countdel + "," + countdel + "," + countdel + ",1,1," + countdel + ",0,0,0,0," + countdel + "," + countdel + ",0,0,null);";
                    sql = "insert into VotingSession values(" + voting_session_id.ToString() + "," + Agenda_Id + "," + ConferrenceId + ",1," + version.ToString() + ",CURRENT_TIMESTAMP," + countdel + ",0,0,0,0," + countdel + ",0," + countdel + "," + countdel + "," + countdel + ",1,1," + countdel + ",0,0,0," + countdel + ",0," + countdel + ",0,0,null);";
                    
                    // AddToEventLog("VotingButton", sql, false);
                    dbcDIS.sqlExecute(sql);
                    foreach (Delegate delitem in listDelegates)
                    {
                        sql = "insert into VotingResult (VotingSession_id,LogDelegate_id,Present,Vote1,Vote2,Vote3,Vote4,Vote5,Parameter,Weight,CastByDelegate_id,Seat_id) values(" + voting_session_id.ToString() + "," + delitem.delegate_id + ",1,1,0,0,0,0,'T',1,0," + delitem.delegate_id + ");";
                        //AddToEventLog("VotingButton", sql, false);
                        dbcDIS.sqlExecute(sql);
                    }
                    sendVotingResultToService(voting_session_id.ToString(), listDelegates);
                    sendIndividualResults(Agenda_Name, Agenda_Id, voting_session_id.ToString(), listDelegates);
                    sql = "update ID set NextId=" + (voting_session_id + 1).ToString() + " where Id=0";
                    //AddToEventLog("VotingButton", sql, false);
                    dbcDIS.sqlExecute(sql);
                    if (reindex)
                    {
                        sql = "ALTER INDEX ALL ON VotingSession REBUILD";
                       // AddToEventLog("VotingButton", sql, false);
                        dbcDIS.sqlExecute(sql);
                        sql = "ALTER INDEX ALL ON VotingResult REBUILD";
                       // AddToEventLog("VotingButton", sql, false);
                        dbcDIS.sqlExecute(sql);
                    }
                    Window6 diag = new Window6();
                    diag.ShowDialog();
                    diag.button1.Tag = "0";
                    try
                    {
                        //Process process = Process.GetProcessesByName("prjCUA")[0];
                        //process.Kill();
                        //String path = process.MainModule.FileName;
                        //Process.Start(path);
                    }
                    catch (Exception ex) { }
                }
                else
                {
                    Window3 diag = new Window3();
                    diag.ShowDialog();
                    diag.button1.Tag = "0";
                }
            }
            else
            {
                Window4 diag = new Window4();
                diag.ShowDialog();
                diag.button1.Tag = "0";
            }
            
        }

        public static void sendVotingResultToService(string voting_session_id,List<Delegate> listDelegates)
        {
            string conclusionPart = "(";
            foreach (Delegate delitem in listDelegates)
            {
                conclusionPart = conclusionPart + delitem.FirstName + " " + delitem.LastName + "(IND),";
            }
            if (conclusionPart.Length > 0)
            {
                conclusionPart = conclusionPart.Substring(0, conclusionPart.Length - 1) + ")";
            }
                string resultXml = "<newdataset>" +
                "<session>" +
                "<session_id>"+voting_session_id+"</session_id>" +
                "<version>1</version>" +
                "<date>"+getDate()+"T"+getTime()+".000000+03:00</date>" +
                "<passedresult>1</passedresult>" +
                "<passedresulttext>PRIIMTAS</passedresulttext>" +
                "<result1>"+listDelegates.Count.ToString()+"</result1>" +
                "<result2>0</result2>" +
                "<result3>0</result3>" +
                "<result4>0</result4>" +
                "<result5>0</result5>" +
                "<result6>" + listDelegates.Count.ToString() + "</result6>" +
                "<result7>0</result7>" +
                "<result8>0</result8>" +
                "<result9>0</result9>" +
                "<result1label>UŽ</result1label>" +
                "<result2label>SUSILAIKĖ</result2label>" +
                "<result3label>PRIEŠ</result3label>" +
                "<result4label />" +
                "<result5label>NEBALSAVO</result5label>" +
                "<result6label>DALYVAUJA</result6label>" +
                "<result7label />" +
                "<result8label />" +
                "<result9label />" +
                "<conclusion>Priimtas" + (char)10 + (char)10 +
                listDelegates.Count.ToString() + " balsavo už "+conclusionPart + (char)10 + (char)10 +
                "0 susilaikė" + (char)10 + (char)10 +
                "0 balsavo prieš" + (char)10 + (char)10 +
                "</conclusion>" +
                "</session>" +
                "</newdataset>";
            object rez = WsProxy.CallWebService(WebService, "WebServiceSimulator", "VotingStop", new string[] { resultXml });
        }

        public static void startVoting(string name,string agenda_id)
        {
            string VotingNameXml = "<newdataset>" +
                "<currentsubject>" +
                "<level>1</level>" +
                "<name>"+name+"</name>" +
                "<description />" +
                "<shortdescription />" +
                "<agenda_id>" + agenda_id + "</agenda_id>" +
                "<import_id />" +
                "</currentsubject>" +
                "<timestamp>" +
                "<eventtime>" + getDate() + "T" + getTime() + ".000000+03:00</eventtime>" +
                "</timestamp>" +
                "</newdataset>";
            object rez = WsProxy.CallWebService(WebService, "WebServiceSimulator", "VotingStart", new string[] { VotingNameXml });
        }

        public static void sendIndividualResults(string name, string agenda_id, string voting_session_id, List<Delegate> listDelegates)
        {
            string individualResultXml="<newdataset>"+
                "<currentsubject>"+
                "<level>1</level>"+
                "<name>"+name+"</name>"+
                "<description />"+
                "<shortdescription />"+
                "<agenda_id>" + agenda_id + "</agenda_id>" +
                "<import_id />"+
                "</currentsubject>";

            foreach (Delegate delitem in listDelegates)
            {
                individualResultXml = individualResultXml + "<result>" +
                  "<session_id>" + voting_session_id + "</session_id>" +
                  "<name>" + delitem.FirstName + " " + delitem.LastName+ "</name>" +
                  "<delegate_id>"+delitem.delegate_id+"</delegate_id>" +
                  "<voteweight>1</voteweight>" +
                  "<vote>1</vote>" +
                  "<votetext>Už</votetext>" +
                "</result>";
            }

              individualResultXml = individualResultXml + "<timestamp>" +
                "<eventtime>" + getDate() + "T" + getTime() + ".000000+03:00</eventtime>" +
              "</timestamp>" +
              "</newdataset>";
              object rez = WsProxy.CallWebService(WebService, "WebServiceSimulator", "IndividualVotingResult", new string[] { individualResultXml });
        }
    }
}
